﻿/******************************************************************************
    myBoard is a port of MacOS X dashboard application for windows.
    Copyright (C) 2007,2008  by Yann ALET
    Email : yann.alet@gmail.com

    myBoard is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    myBoard is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
****************************************************************************/

using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using myBoard.Framework;
using Guide.Config;
using System.Diagnostics;
using System.Reflection;
using System.ComponentModel;
using Guide.External;
using Guide.XMLTV;
using System.Collections.Generic;
using System.Text;
using System.Windows.Media.Imaging;

namespace Guide
{
	public partial class myGuide : IMagnet , IRequiresStorage, IFlip
	{
        Storyboard _showProgramDetailsSB;
        Storyboard _hideProgramDetailsSB;
        Storyboard _startRefreshSB;
        Storyboard _endRefreshSB;
        Storyboard _showRefreshBtSB;
        Storyboard _retractRefreshBtSB;
        Configuration _currentConfig;
        XMLTV.Guide _guide;
        ObjectDataProvider _grabbersDataProvider;
        ObjectDataProvider _guideDataProvider;
        public myGuide()
		{
			this.InitializeComponent();            

            _showProgramDetailsSB = this.Resources["ShowProgramDetails"] as Storyboard; 
            _hideProgramDetailsSB = this.Resources["HideProgramDetails"] as Storyboard;
            _startRefreshSB = this.Resources["StartRefresh"] as Storyboard;
            _endRefreshSB = this.Resources["EndRefresh"] as Storyboard;
            _showRefreshBtSB = this.Resources["ShowRefreshBt"] as Storyboard;
            _retractRefreshBtSB = this.Resources["RetractRefreshBt"] as Storyboard;
            _guideDataProvider = this.Resources["GuideDS"] as ObjectDataProvider;
            _guideDataProvider.ObjectInstance = Instances.Guide;
            _grabbersDataProvider = this.Resources["GrabbersDS"] as ObjectDataProvider;
            _grabbersDataProvider.ObjectInstance = Instances.Grabbers;
            _frontFlipButton.Click += new RoutedEventHandler(_frontFlipButton_Click);
            _saveBt.Click += new RoutedEventHandler(_saveBt_Click);
            _refreshBt.Click += new RoutedEventHandler(_refreshBt_Click);
            _startRefreshSB.Completed += new EventHandler(_startRefreshSB_Completed);
            _cancelBt.Click += new RoutedEventHandler(_cancelBt_Click);
        }

        private void _backBt_Click(object sender, RoutedEventArgs e)
        {
            this.BeginStoryboard(_hideProgramDetailsSB);
        }

        void _cancelBt_Click(object sender, RoutedEventArgs e)
        {
            if (this.FlipRequested != null)
            {
                this.FlipRequested(MagnetSides.Front);
            }
        }
        
        void _frontFlipButton_Click(object sender, RoutedEventArgs e)
        {
            if (FlipRequested != null)
                FlipRequested(MagnetSides.Back);
        }

        void _guide_RefreshCompleted(GrabbersEnum grabber)
        {
            ReloadActiveProgramXmlFile();
            _loader.CloseLoader();
            _channels.BeginStoryboard(_endRefreshSB);
            BeginStoryboard(_showRefreshBtSB);
        }

        void _refreshBt_Click(object sender, RoutedEventArgs e)
        {
            _errorBlock.Visibility = Visibility.Collapsed;
            this.BeginStoryboard(this._retractRefreshBtSB);
            _channels.BeginStoryboard(_startRefreshSB);
            _guide.Refresh((GrabbersEnum)Enum.Parse(typeof(GrabbersEnum), this._currentConfig.SelectedGrabber));          
        }

        void _saveBt_Click(object sender, RoutedEventArgs e)
        {
            this._currentConfig.SelectedGrabber = this._countriesList.SelectedItem.ToString();
            string path = Path.Combine(Controller.SharedProperties.MagnetStorage.StorageDirectory.FullName, ".xmltv");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string str2 = this._currentConfig.SelectedGrabber + ".conf";
            using (FileStream stream = new FileStream(Path.Combine(path, str2), FileMode.Create))
            {
                UTF8Encoding encoding = new UTF8Encoding();
                string userChannelsConfiguration = Instances.Grabbers.ActiveGrabber.GetUserChannelsConfiguration();
                byte[] bytes = encoding.GetBytes(userChannelsConfiguration);
                stream.Write(bytes, 0, bytes.Length);
                stream.Close();
            }
            if (this.FlipRequested != null)
            {
                this.FlipRequested(MagnetSides.Front);
            }
            this._refreshBt_Click(this, null);

        }

        void _startRefreshSB_Completed(object sender, EventArgs e)
        {
            _loader.ShowLoader();
        }

        private void ActiveConfiguration(Configuration _currentConfig)
        {
            _guide = SingletonFactory.GetInstance<XMLTV.Guide>();
            _guide.WorkingPath = Controller.SharedProperties.MagnetStorage.StorageDirectory.FullName;
            _guide.RefreshCompleted += new XMLTV.Guide.OnRefreshCompleted(this._guide_RefreshCompleted);
            Instances.Grabbers.ActiveGrabber = Instances.Grabbers[(GrabbersEnum)Enum.Parse(typeof(GrabbersEnum), _currentConfig.SelectedGrabber)];
            ReloadActiveProgramXmlFile();
        }

        private void ReloadActiveProgramXmlFile()
        {
            Instances.Guide.ProgramXmlFile = Path.Combine(Controller.SharedProperties.MagnetStorage.StorageDirectory.FullName, this._currentConfig.SelectedGrabber + ".xml");
        }

        #region IRequiresStorage Members

        public void GetStorage(Storage storage)
        {
            Controller.SharedProperties.MagnetStorage = storage;
            _currentConfig = Serialization.DeSerialize(Path.Combine(Controller.SharedProperties.MagnetStorage.StorageDirectory.FullName, "settings.xml"));
            if (_currentConfig == null)
            {
                _errorBlock.Visibility = Visibility.Visible;
                _refreshBt.Visibility = Visibility.Collapsed;
                _currentConfig = new Configuration();
                ActiveConfiguration(_currentConfig);
            }
            else
            {
                ActiveConfiguration(_currentConfig);
            }
        }

        public void SaveState()
        {
            Serialization.Serialize(this._currentConfig, Path.Combine(Controller.SharedProperties.MagnetStorage.StorageDirectory.FullName, "settings.xml"));
        }

        #endregion

        private void Grid_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            this._programDetails.DataContext = ((Grid)sender).DataContext;
            this.BeginStoryboard(_showProgramDetailsSB);
        }
        

        #region IMagnet Members

        public string StoreID 
        {
            get
            { return "{C03461C3-11D8-4d73-94E1-B93C44C7D3C0}"; }
        }

        public event OnFlipRequested FlipRequested;

        public Panel GetBackSide()
        {
            return _backSide;
        }

        public Panel GetFlipZone()
        {
            return _flipZone;
        }

        public Panel GetFrontSide()
        {
            return _frontSide;
        }

        public BitmapImage Icon
        {
            get
            {
                return ResourcesAccess.GetBitmapImageFromResource(Assembly.GetExecutingAssembly(), "Guide.television.png");
            }
        }

        BitmapImage _thumbnail;


        public BitmapImage Thumbnail
        {
            get
            {
                if (_thumbnail == null)
                {
                    _thumbnail = Tools.GetBitmapImageFromFrameworkElement(this);
                }
                return _thumbnail;
            }
        }

        public string MagnetName
        {
            get { return "myGuide"; }
        }

        public void Terminate()
        {
            SaveState();
            
        }

        #endregion

        
    }
}